package com.ptszyxx.popose.module.main;

import android.content.Intent;
import android.os.Bundle;

import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.lifecycle.ViewModelProviders;

import com.ptszyxx.popose.BR;
import com.ptszyxx.popose.BuildConfig;
import com.ptszyxx.popose.R;
import com.ptszyxx.popose.common.constants.BundleConstant;
import com.ptszyxx.popose.common.enums.BannerEventEnum;
import com.ptszyxx.popose.common.enums.MainTabEnum;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ptszyxx.popose.common.utils.YChatUtil;
import com.ptszyxx.popose.common.utils.YMonitorUtil;
import com.ptszyxx.popose.common.utils.sensitive.YSensitiveUtil;
import com.ptszyxx.popose.databinding.ActivityMainBinding;
import com.ptszyxx.popose.module.main.dynamic.DynamicFragment;
import com.ptszyxx.popose.module.main.home.HomeFragment;
import com.ptszyxx.popose.module.main.map.MapFragment;
import com.ptszyxx.popose.module.main.message.MessageFragment;
import com.ptszyxx.popose.module.main.mine.MineFragment;
import com.ptszyxx.popose.module.main.mine.MineWorldFragment;
import com.ptszyxx.popose.module.main.popo.PopoFragment;
import com.ptszyxx.popose.module.main.swipe.SwipeFragment;
import com.ptszyxx.popose.module.main.trip.TripFragment;
import com.ysg.base.BaseActivity;
import com.ysg.http.data.AppViewModelFactory;
import com.ysg.http.data.entity.mine.VersionEntity;
import com.ysg.utils.YConfigUtil;
import com.ysg.utils.YDialogUtil;
import com.ysg.utils.YPermissionUtil;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.tab.CustomTabEntity;
import com.ysg.widget.tab.OnTabSelectListener;
import com.ysg.widget.tab.TabEntity;

import java.lang.ref.WeakReference;
import java.util.ArrayList;

public class MainActivity extends BaseActivity<ActivityMainBinding, MainVM> {
    private String homeTitle, dynamicTitle, mapTitle, messageTitle, mineTitle;
    private MainTabEnum tabEnum;
    private String[] mTitles;
//    R.mipmap.tab_dynamics_unselect, R.mipmap.tab_dynamics_select,
    private int[] mIconUnselectIds = { R.mipmap.tab_home_unselect, R.mipmap.tab_dynamics_unselect, R.mipmap.tab_message_unselect, R.mipmap.tab_mine_unselect};
    private int[] mIconSelectIds = { R.mipmap.tab_home_select, R.mipmap.tab_dynamics_select,  R.mipmap.tab_message_select, R.mipmap.tab_mine_select};
    private static WeakReference<MainActivity> instance;

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @Override
    public MainVM initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(MainVM.class);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (intent != null){
            String tab = intent.getStringExtra(BundleConstant.TAB);
            tabEnum = MainTabEnum.get(tab);
            if (tabEnum != null){
                binding.tab.setCurrentTab(tabEnum.getType());
                showFragment(tabEnum.getType());
            }
        }
    }

    private String chatUserId, chatUserName, chatUserPic;
    @Override
    public void initParam() {
        homeTitle = getResources().getString(R.string.main_tab_home);
        dynamicTitle = getResources().getString(R.string.main_tab_dynamic);
        mapTitle = getResources().getString(R.string.main_tab_map);
        messageTitle = getResources().getString(R.string.main_tab_message);
        mineTitle = getResources().getString(R.string.main_tab_mine);

//        dynamicTitle
        mTitles = new String[]{homeTitle, dynamicTitle, messageTitle, mineTitle};

        Intent intent = getIntent();
        if (intent != null){
            chatUserId = intent.getStringExtra(BundleConstant.CHAT_USER_ID);
            chatUserName = intent.getStringExtra(BundleConstant.CHAT_USER_NAME);
            chatUserPic = intent.getStringExtra(BundleConstant.CHAT_USER_PIC);
        }
    }

    public static void finishMainActivity() {
        if (instance != null && instance.get() != null) {
            instance.get().finish();
        }
    }

    @Override
    public void initData() {
        super.initData();
        YMonitorUtil.getInstance().submit(BannerEventEnum.active);
        viewModel.requestSetup();
//        viewModel.requestTicketConfig();
        viewModel.requestImSign();
//        viewModel.requestVersion();
        viewModel.requestVip();
        downloadSensitive();
        viewModel.requestUser();
    }

    @Override
    public void initView() {
        instance = new WeakReference<>(this);
        initTab();
    }

    private ArrayList<CustomTabEntity> mTabEntities = new ArrayList<>();
    private void initTab() {
        for (int i = 0; i < mTitles.length; i++) {
            mTabEntities.add(new TabEntity(mTitles[i], mIconSelectIds[i], mIconUnselectIds[i]));
        }
        binding.tab.setTabData(mTabEntities);
        binding.tab.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                String title = mTitles[position];
                showFragment(position);
//                if (YStringUtil.eq(mapTitle, title)){
//                    requestLocation(position);
//                }else{
//                    showFragment(position);
//                }
            }

            @Override
            public void onTabReselect(int position) {
            }
        });

        binding.tab.setCurrentTab(getMainTab());
        showFragment(getMainTab());
    }

    private HomeFragment homeFragment;
    private DynamicFragment dynamicFragment;
    private MapFragment mapFragment;
    private TripFragment tripFragment;
    private PopoFragment popoFragment;
    private SwipeFragment swipeFragment;
    private MessageFragment messageFragment;
    private MineFragment mineFragment;
    private MineWorldFragment mineWorldFragment;
    public void showFragment(int tab){
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction transaction = fragmentManager.beginTransaction();

        if (homeFragment != null) transaction.hide(homeFragment);
        if (dynamicFragment != null) transaction.hide(dynamicFragment);
        if (mapFragment != null) transaction.hide(mapFragment);
        if (tripFragment != null) transaction.hide(tripFragment);
        if (popoFragment != null) transaction.hide(popoFragment);
        if (swipeFragment != null) transaction.hide(swipeFragment);
        if (messageFragment != null) transaction.hide(messageFragment);
        if (mineFragment != null) transaction.hide(mineFragment);
        if (mineWorldFragment != null) transaction.hide(mineWorldFragment);

        switch (tab){
            case 0:
                if (homeFragment == null){
                    homeFragment = new HomeFragment();
                    transaction.add(R.id.fragmentManager, homeFragment);
                }else{
                    transaction.show(homeFragment);
                }
                binding.tab.setBackgroundColor(getResources().getColor(R.color.tabBgBlack));
                break;
            case 1:
                if (dynamicFragment == null){
                    dynamicFragment = new DynamicFragment();
                    transaction.add(R.id.fragmentManager, dynamicFragment);
                }else{
                    transaction.show(dynamicFragment);
                }
                binding.tab.setBackgroundColor(getResources().getColor(R.color.tabBgWhite));
                break;
            case 2:
                if (messageFragment == null){
                    messageFragment = new MessageFragment();
                    transaction.add(R.id.fragmentManager, messageFragment);
                }else{
                    transaction.show(messageFragment);
                }
                binding.tab.setBackgroundColor(getResources().getColor(R.color.tabBgWhite));
                break;
            case 3:
                if (mineWorldFragment == null){
                    mineWorldFragment = new MineWorldFragment();
                    transaction.add(R.id.fragmentManager, mineWorldFragment);
                }else{
                    transaction.show(mineWorldFragment);
                }
                binding.tab.setBackgroundColor(getResources().getColor(R.color.tabBgBlack));
                break;
        }
        transaction.commit();
    }

    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.uc.onImSignEvent.observe(this, o -> getUnReadMessage());
        viewModel.uc.onUpdateVersionEvent.observe(this, o -> showDialogVersion((VersionEntity)o));
    }

    /**
     * 设置未读数量
     */
    private void setUnReadCount(long unReadCount){
        int tab = getMessageTab();
        if (unReadCount > 0){
            binding.tab.showMsg(tab, (int) unReadCount);
        }else{
            binding.tab.hideMsg(tab);
        }
    }

    public int getMessageTab(){
        for(int i = 0; i < mTitles.length; i++){
            if (YStringUtil.eq(messageTitle, mTitles[i])){
                return i;
            }
        }
        return 3;
    }
    public int getMainTab(){
        for(int i = 0; i < mTitles.length; i++){
            if (YStringUtil.eq(YConfigUtil.getMainTabName(), mTitles[i])){
                return i;
            }
        }
        return 0;
    }

    /**
     * 获取未读信息数量
     */
    private void getUnReadMessage() {
//        V2TIMManager.getConversationManager().getTotalUnreadMessageCount(new V2TIMValueCallback<Long>() {
//            @Override
//            public void onSuccess(Long aLong) {
//                setUnReadCount(aLong);
//            }
//
//            @Override
//            public void onError(int code, String desc) {
//                Log.e("获取未读信息数量出错：", "code:"+code + " ;desc:"+desc);
//            }
//        });
//        V2TIMManager.getConversationManager().addConversationListener(new V2TIMConversationListener() {
//            @Override
//            public void onTotalUnreadMessageCountChanged(long totalUnreadCount) {
//                super.onTotalUnreadMessageCountChanged(totalUnreadCount);
//                setUnReadCount(totalUnreadCount);
//            }
//        });
        YChatUtil.getInstance().setUnReadCount(count -> setUnReadCount(count));

        //点击通知栏：跳到聊天
        if (YStringUtil.isNotEmpty(chatUserId)){
            YActivityUtil.getInstance().jumpChat(viewModel, chatUserId, chatUserName, chatUserPic);
        }
    }

    /**
     * 版本更新
     */
    private void showDialogVersion(VersionEntity entity) {
        YDialogUtil.getInstance().showVersion(this, entity, BuildConfig.VERSION_CODE);
    }

    private void requestLocation(int tab) {
        YPermissionUtil.requestLocation(this, "申请定位权限：用于popo圈-附近中的定位功能", new YPermissionUtil.OnPermissionListener() {
            @Override
            public void onSuccess() {
                showFragment(tab);
            }

            @Override
            public void onError() {
                YToastUtil.showLong("关闭定位权限，不能正常使用");
            }
        });
    }

    /**
     * 下载敏感词
     */
    private void downloadSensitive(){
        YSensitiveUtil.onDownloadSensitiveFile();
    }


}
